<?php
class SiteManager_ObjectController extends SiteManagerController
{

   	public function indexAction() {
		$iPage = intval($this->getRequest()->getParam('page', 1));
		$id = (int) $this->getRequest()->getParam('id', 0);
		$objname = trim($this->getRequest()->getParam('objname', ''));
		if ($id !== 0) {
			$this->view->objects = Obj_Object::getAllPaginatedObjectsByCondition($iPage, 'ID = '.$id, false);
			$this->view->id = $id;
		}
		elseif ($objname != '') {
			$this->view->objects = Obj_Object::getAllPaginatedObjectsByCondition($iPage, "Name LIKE ('%".mysql_escape_string($objname)."%')", false);
			$this->view->objname = $objname;
		}
		else $this->view->objects = Obj_Object::getAllPaginatedObjects($iPage, false); 
    }

   	public function editAction() {
   		$iPage = intval($this->getRequest()->getParam('page', 1));
   		$this->view->pageNumber = $iPage;
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$addnew = intval($this->getRequest()->getParam('addnew', 0)) === 1 ? true : false;
    	$arObject = Obj_Object::getObject($id);
    	// get countries
    	$arCountry = Obj_Country::getCountries();
    	$countries = array();
    	$countries[0] = _('Выберите страну...');
    	foreach ($arCountry as $v) {
    		$countries[$v['ID']] = $v['Name'];
    	}    	
    	$this->view->countries = $countries;
    	$this->view->country = $arObject['CountryID'];
    	// get regions
    	$ar = Obj_Region::getRegions($arObject['CountryID']);
    	$regions = array();
    	$regions[0] = _('Выберите регион...');
        foreach ($ar as $v) {
    		$regions[$v['ID']] = $v['Name'];
    	}    	
    	$this->view->regions = $regions;
    	$this->view->region = $arObject['RegionID'];
    	
    	// get cities
    	$arCities = Obj_City::getCities($arObject['RegionID']);
    	$cities = array();
    	$cities[0] = _('Выберите город...');
    	foreach ($arCities as $v) {
    		$cities[$v['ID']] = $v['Name'];
    	}
    	$this->view->cities = $cities;
    	$this->view->city = $arObject['CityID'];
    	
    	// get locations
    	$ar = Obj_Location::getLocations($arObject['CityID']);
    	$locations = array();
    	$locations[0] = _('Выберите район...');
    	foreach ($ar as $v) {
    		$locations[$v['ID']] = $v['Name'];
    	}    	
    	$this->view->locations = $locations;
    	$this->view->location = $arObject['LocationID'];
    	
    	// get object type
    	$object_types = Obj_ObjectType::getObjectTypes();
    	$_object_types = array();
    	foreach ($object_types as $_v){
    		$_object_types[$_v['ID']] = $_v['Name'];
    	}
    	$this->view->ObjectTypeId = $_object_types;
		$this->view->CurrentObjectTypeId = $arObject['ObjectTypeId'];
    	
		$arrCurrency =array('1'=>'$', 
							'2' => '€',
							'3' => 'RUB');
		$this->view->Currencies = $arrCurrency;
    	$this->view->Сurrency = $arObject['Сurrency'];
    	$arrImages = Obj_Image::getImages($id);
    	$this->view->images = $arrImages;
    	//print_r($arObject);
    	//die();
    	if ($addnew || $arObject === false) {
    		$this->view->object = array(
    			'ID' 				=> 0,
				'CountryID' 		=> 0,
				'RegionID' 			=> 0,
				'CityID' 			=> 0,
				'LocationID' 		=> 0,
				'Name' 				=> '',
				'Alias' 			=> '',
				'ShortDescription' 	=> '',
				'FullDescription' 	=> '',
    			'Adress' 			=> '',
    			'Attribute' 		=> OBJECT_SALE,
    			'Sort'			 	=> 0,
				'DistanceToSea' 	=> '',
				'DistanceToAirport' => '',
				'ObjectTypeId' 		=> 0,
				'YearOfConstruction'=> '',
				'Floor' 			=> '',
				'Area' 				=> '',
				'AreaTo' 			=> '',
				'NumberOfBedrooms' 	=> '',
				'NumberOfBathrooms' => '',
				'SwimmingPool' 		=> 0,
				'Parking' 			=> 0,
				'Security' 			=> 0,
				'Elevator' 			=> 0,
				'ChildrensPool' 	=> 0,
				'Playground' 		=> 0,
				'Heating' 			=> 0,
				'HotWater' 			=> 0,
    			'Сurrency'			=> '',
				'Price' 			=> '',
				'PriceTo' 			=> '',
				'Latitude' 			=> '',
				'Longitude' 		=> '',
				'Zoom' 				=> '',
				'Active' 			=> 0,
				'SeoTitle' 			=> '',
				'SeoKeywords' 		=> '',
				'SeoDescription' 	=> '',
				'Agent' 			=> 0,
				'FronPage' 			=> 0,
    		);
    	}
    	else {
    		$this->view->object = $arObject;	
    	}

    }

    public function reloadRegionsAction() {
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$arRegions = Obj_Region::getRegions($id);
    	$regions = array();
    	if ($arRegions !== false) {
    		$regions[0] = _('Выберите регион...');
    		foreach ($arRegions as $v) $regions[$v['ID']] = $v['Name'];
    	}
    	$this->_helper->json(array('error' => 0, 'RegionID' => $regions), true, false);
    }

    public function reloadCitiesAction() {
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$arCities = Obj_City::getCities($id);
    	$cities = array();
    	if ($arCities !== false){
    		 $cities[0] = _('Выберите город...');
    		 foreach ($arCities as $v) $cities[$v['ID']] = $v['Name'];    	
    	}
    	$this->_helper->json(array('error' => 0, 'cities' => $cities), true, false);
    }

    public function reloadLocationsAction() {
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$arLocations = Obj_Location::getLocations($id);
    	$locations = array();
    	if ($arLocations !== false) {
    		$locations[0] = _('Выберите район...');
    		foreach ($arLocations as $v) $locations[$v['ID']] = $v['Name'];    	
    	}
    	$this->_helper->json(array('error' => 0, 'locations' => $locations), true, false);
    }

    public function saveAction() {
    	$arObject = array();
		$arObject['ID'] = (int) $this->getRequest()->getParam('ID', 0);
		$arObject['CountryID'] = (int) $this->getRequest()->getParam('CountryID', 0);
		$arObject['RegionID'] = (int) $this->getRequest()->getParam('RegionID', 0);
		$arObject['CityID'] = (int) $this->getRequest()->getParam('CityID', 0);
		$arObject['LocationID'] = (int) $this->getRequest()->getParam('LocationID', 0);
		$arObject['Name'] = $this->getRequest()->getParam('Name', null);
		$arObject['Alias'] = Obj_Text::translit($arObject['Name']);
		$arObject['ShortDescription'] = $this->getRequest()->getParam('ShortDescription', null);
		$arObject['FullDescription'] = Obj_Text::removeHTMLComments($this->getRequest()->getParam('FullDescription', ''));
		$arObject['Adress'] = $this->getRequest()->getParam('Adress', '');
		$arObject['Attribute'] = $this->getRequest()->getParam('Attribute', OBJECT_SALE);
		$arObject['Sort'] = (int) $this->getRequest()->getParam('Sort', 0);		
		$arObject['DistanceToSea'] = (int)$this->getRequest()->getParam('DistanceToSea', 0);
		$arObject['DistanceToAirport'] = (int)$this->getRequest()->getParam('DistanceToAirport', 0);
		$arObject['ObjectTypeId'] = (int)$this->getRequest()->getParam('ObjectTypeId', 0);
		$arObject['YearOfConstruction'] = (int)$this->getRequest()->getParam('YearOfConstruction', 0);
		$arObject['Floor'] = (int)$this->getRequest()->getParam('Floor', 0);
		$arObject['Area'] = (int)$this->getRequest()->getParam('Area', 0);
		$arObject['AreaTo'] = (int)$this->getRequest()->getParam('AreaTo', 0);
		$arObject['NumberOfBedrooms'] = trim($this->getRequest()->getParam('NumberOfBedrooms', ''));
		$arObject['NumberOfBathrooms'] = (int)$this->getRequest()->getParam('NumberOfBathrooms', 0);
		$arObject['SwimmingPool'] = ($this->getRequest()->getParam('SwimmingPool'))?1:0;
		$arObject['Parking'] = ($this->getRequest()->getParam('Parking'))?1:0;
		$arObject['Security'] = ($this->getRequest()->getParam('Security'))?1:0;
		$arObject['Elevator'] = ($this->getRequest()->getParam('Elevator'))?1:0;
		$arObject['ChildrensPool'] = ($this->getRequest()->getParam('ChildrensPool'))?1:0;
		$arObject['Playground'] = ($this->getRequest()->getParam('Playground'))?1:0;
		$arObject['Heating'] = ($this->getRequest()->getParam('Heating'))?1:0;
		$arObject['HotWater'] = ($this->getRequest()->getParam('HotWater'))?1:0;		
		$arObject['Сurrency'] = $this->getRequest()->getParam('Сurrency', 0);		
		$arObject['Price'] = (int)$this->getRequest()->getParam('Price', 0);
		$arObject['PriceTo'] = (int)$this->getRequest()->getParam('PriceTo', 0);
		$arObject['Active'] = ($this->getRequest()->getParam('Active'))?1:0;
		$arObject['SeoTitle'] = $this->getRequest()->getParam('SeoTitle', '');
		$arObject['SeoKeywords'] = $this->getRequest()->getParam('SeoKeywords', '');
		$arObject['SeoDescription'] = $this->getRequest()->getParam('SeoDescription', '');
		$arObject['Agent'] = $this->getRequest()->getParam('Agent', 0);
		$arObject['FronPage'] = ($this->getRequest()->getParam('FronPage'))?1:0;

		$errors = array('is_error' => 0, 'err_string' => array());
		if(!$arObject['CountryID']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Не верно указана страна";
		}
		if(!$arObject['RegionID']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Не верно указан регион";
		}
		if(!$arObject['CityID']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Не верно указан город";
		}
		if(!$arObject['LocationID']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Не верно указан район";
		}
		if(!$arObject['Name']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Укажите название объекта";
		}
		
		$arObject['Alias'] = Obj_Object::checkAlias($arObject['CountryID'], $arObject['RegionID'], $arObject['CityID'], $arObject['LocationID'], $arObject['Alias']);
		
		if(!$arObject['ShortDescription']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Заполните поле короткое описание";
		}
		if(!$arObject['ObjectTypeId']){
			$errors['is_error'] = 1;
			$errors['err_string'][] = "Не верно указан тип объекта";
		}	
		if($errors['is_error'] == 1){
			
	    	// get countries
	    	$arCountry = Obj_Country::getCountries();
	    	$countries = array();
	    	$countries[0] = _('Выберите страну...');
	    	foreach ($arCountry as $v) {
	    		$countries[$v['ID']] = $v['Name'];
	    	}	    	
	    	$this->view->countries = $countries;
	    	$this->view->country = $arObject['CountryID'];
    	
	    	// get regions
	    	$ar = Obj_Region::getRegions($arObject['CountryID']);
	    	$regions = array();
	    	$regions[0] = _('Выберите регион...');
	        foreach ($ar as $v) {
	    		$regions[$v['ID']] = $v['Name'];
	    	}	    	
	    	$this->view->regions = $regions;
	    	$this->view->region = $arObject['RegionID'];
		
	    	// get cities
	    	$arCities = Obj_City::getCities($arObject['RegionID']);
	    	$cities = array();
	    	$cities[0] = _('Выберите город...');
	    	foreach ($arCities as $v) {
	    		$cities[$v['ID']] = $v['Name'];
	    	}	    	
	    	$this->view->cities = $cities;
	    	$this->view->city = $arObject['CityID'];

	    	// get locations
	    	$ar = Obj_Location::getLocations($arObject['CityID']);
	    	$locations = array();
	    	$locations[0] = _('Выберите район...');
	    	foreach ($ar as $v) {
	    		$locations[$v['ID']] = $v['Name'];
	    	}	    	
	    	$this->view->locations = $locations;
			$this->view->location = $arObject['LocationID'];
			
			$this->view->error = $errors['err_string'];
			$this->view->object = $arObject;
	    	// get object type
	    	$object_types = Obj_ObjectType::getObjectTypes();
	    	$_object_types = array();
	    	foreach ($object_types as $_v){
	    		$_object_types[$_v['ID']] = $_v['Name'];
	    	}
	    	$this->view->ObjectTypeId = $_object_types;
			$this->view->CurrentObjectTypeId = $arObject['ObjectTypeId'];
	    	
			$arrCurrency =array(
								'1'=>'$', 
								'2' => '€',
								'3' => 'RUR');
			$this->view->Currencies = $arrCurrency;
	    	$this->view->Сurrency = $arObject['Сurrency'];
	    	$object_types = Obj_ObjectType::getObjectTypes();
	    	$_object_types = array();
	    	foreach ($object_types as $_v){
	    		$_object_types[$_v['ID']] = $_v['Name'];
	    	}
	    	$this->view->ObjectTypeId = $_object_types;
			$this->_helper->viewRenderer->setRender('edit');
			return;
		}		
		$oid = $arObject['ID'] != 0 ? (int) $arObject['ID'] : 0;
		if ($oid === 0) unset($arObject['ID']);
		$oid = Obj_Object::saveObject($arObject, $oid);
		$arObject['ID'] = $oid;
    	if ($arObject['Active'] === 1){
    		Obj_System_SearchIndex::write($oid, CONTENT_TYPE_OBJECT, $arObject['Name'], $arObject['ShortDescription'], $arObject['FullDescription']);
    	} else {
    		Obj_System_SearchIndex::delete($oid, CONTENT_TYPE_OBJECT);
    	}    	
    	$preMain = $this->getRequest()->getParam('main');
		$_ = explode("_", $preMain);      	
    	$arObject['Main'] = (int)$_[sizeOf($_)-1];
		$iPage = intval($this->getRequest()->getParam('page', 1));
		foreach ($_FILES["objectFile"]["error"] as $key => $error) {
			if ($error == UPLOAD_ERR_OK) {
				$mainImage = ((int)$key == $arObject['Main']-1)?1:0;	
				$image_arr = array(	'name' 		=> $_FILES["objectFile"]["name"][$key],
									'tmp_name' 	=> $_FILES["objectFile"]["tmp_name"][$key],
									'size' 		=> $_FILES["objectFile"]["size"][$key],
									'type' 		=> $_FILES["objectFile"]["type"][$key],
									'object' 	=> $oid,
									'main' 		=> $mainImage
								 );
				$image = Obj_Image::uploadPhoto($image_arr);
				Obj_Image::saveImage($image, 0);
			} else {
				$this->_redirect('site-manager/country/index/page/'.$iPage);
    			die();
			}
		}
		$this->_redirect('site-manager/object/edit/id/'.$arObject['ID']);
    	die();
    }

    public function deleteAction() {
        if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	Obj_Object::delObject($id);
    	Obj_SpecialOffersSetter::delSpecialOffersSetter($id);
    	Obj_SpecialOffersSetter::delSpecialOffersSetter($id);
    	Obj_System_SearchIndex::delete($id, CONTENT_TYPE_OBJECT);
		$this->_helper->json(array('error' => 2));
    }

    public function deleteObjectImageAction() {
        if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$parent = (int) $this->getRequest()->getParam('parent', 0);
   		Obj_Image::deleteImage($id);
    	$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('action' => 'edit', 'id'=>$parent))), true, false);  
    }

    public function setMainPageAction(){
		if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$parent = (int) $this->getRequest()->getParam('parent', 0);
    	$_images = Obj_Image::getImages($parent);
		foreach($_images as $im){
			$arUpdate = array('Main' => 0);
			Obj_Image::saveImage($arUpdate, (int)$im['ID']);				
		}
		$arMain = array('Main' => 1);
		Obj_Image::saveImage($arMain, $id);
		$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('action' => 'edit', 'id'=>$parent))), true, false);
    }
    
    public function stateChangerAction() {
		if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$arObjects = Obj_Object::getObject($id);
    	if(intval($arObjects['Active']) === 1){
    		$arObjects['Active'] = 0;
    		$oid = Obj_Object::saveObject($arObjects, $id);
    		Obj_System_SearchIndex::delete($oid, CONTENT_TYPE_OBJECT);
    	} else {
    		$arObjects['active'] = 1;
    		$oid = Obj_Object::saveObject($arObjects, $id);
    		Obj_System_SearchIndex::write($oid, CONTENT_TYPE_OBJECT, $arObjects['Name'], $arObjects['ShortDescription'], $arObjects['FullDescription']);
    	}
    	$this->_helper->json(array('error' => 2));
    }
    
    public function showObjectSpecialOffersAction() {
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$special_offers = Obj_SpecialOffer::getAllSpecialOffers(true);

    	$special_offer_node = Obj_SpecialOffersSetter::getSpecialOffersSetterByObject($id);
    	$clear_offers = array();
    	if($special_offer_node){
    		foreach($special_offer_node as $v) {
    			$clear_offers[] = $v['OfferID'];
    		}
    	}
    	$offers_html = "<div id='special_offers_list'>";
    	foreach($special_offers as $v){
    		$checked = (in_array($v['ID'], $clear_offers))?"checked='checked'":"";
    		$offers_html .= "
    		<div class='popup_spec_off'>
    			<div class='off_checkbox_div'>
    				<input type='checkbox' name='".$v['ID']."' ".$checked." class='sp_of' id='spe_offer_".$v['ID']."'/>
    			</div>
    			<div class='off_act_name_div'>
    				<label for='spe_offer_".$v['ID']."'>
    					".$v['Title']."
    				</label>
    			</div>
    		</div>";
    	}
    	$offers_html .= "
		</div>   		
		<div id='save_state'>
			<input type='button' value='"._('Сохранить')."' id='save_special_offers_for_object'/>
		</div>";
    	$this->_helper->json(array('error' => 0, 'data' => $offers_html));
    }
    
    public function setObjectSpecialOffersAction() {
		if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$object_id = (int) $this->getRequest()->getParam('id', 0);
    	$offer_arr = $this->getRequest()->getParam('arrCheckbox', 0);
    	Obj_SpecialOffersSetter::getAllSpecialOffers($object_id);
    	Obj_SpecialOffersSetter::delSpecialOffersSetter($object_id);
    	if((sizeOf($offer_arr)>0) && $offer_arr){
    		foreach($offer_arr as $k => $v){
    			$data = array('OfferID' => $v, 'ObjectID' => $object_id);
    			Obj_SpecialOffersSetter::saveSpecialOffersSetter($data, 0);
    		}
    	} else {
    		$this->_helper->json(array('error' => 2));
    	}
    	$this->_helper->json(array('error' => 2));
    }

    public function showSameObjectsAction() {
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
		
    	$same_objects_node = Obj_SameObjects::getSameObjectsByObject($id);
    	$same_objects = "";
    	if($same_objects_node){
    		foreach($same_objects_node as $v) {
    			$same_objects .= $v['SameID'].",";
    		}
    		$same_objects = substr($same_objects, 0, sizeOf($same_objects)-2);
    	}
    	$offers_html = "
		<div id='popup_same_objects'>
			<div id='same_object_text'>
				
			</div>
			<div id='popup_same_object_input'>
				<input type='text' name='same_objects' id='same_objects_field' maxlength='255' value='".$same_objects."'/>
			</div>
		</div> 		
    	<div id='save_state' style='background: #EDEDED'>
    			<input type='button' value='"._('Сохранить')."' id='save_same_objects_button'/>
		</div>
    	";
    	$this->_helper->json(array('error' => 0, 'data' => $offers_html));
    }
    
    public function setSameObjectsAction() {
		if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$same_limit = 5;
    	$object_id = (int) $this->getRequest()->getParam('id', 0);
    	$same_str = $this->getRequest()->getParam('sameArr', '');
    	Obj_SameObjects::delSameObject($object_id);
    	if(strlen($same_str)>0 && sizeOf(explode(',', $same_str))>0){
	    	$_arr = array_unique(explode(',', $same_str));
	    	$same_arr = array();
	    	foreach($_arr as $v){
	    		if((int)trim($v) != $object_id)
	    			$same_arr[] = (int)trim($v);
	    	}
	    	$count = ((sizeOf($same_arr))>$same_limit-1)?$same_limit:sizeOf($same_arr);
	    	for($i=0; $i<$count; $i++){
	    		$done_data = array('ObjectID' => $object_id, 'SameID' => $same_arr[$i]);
	    		Obj_SameObjects::saveSameObject($done_data, 0);
	    	}
    	}
    	$this->_helper->json(array('error' => 2));
    }
    
    public function groupedDeleteAction(){
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$arDelete = array();
    	$arDelete = $this->getRequest()->getParam('arDelete', null);
    	foreach ($arDelete as $k => $v){
	    	$id = (int) $v;
	    	Obj_Object::delObject($id);
	    	Obj_SpecialOffersSetter::delSpecialOffersSetter($id);
	    	Obj_SpecialOffersSetter::delSpecialOffersSetter($id);
	    	Obj_System_SearchIndex::delete($id, CONTENT_TYPE_OBJECT);
    	}
		$this->_helper->json(array('error' => 2));
    }
}